package com.quantoeugasto.persistencia;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.quantoeugasto.entidade.Ano;
import com.quantoeugasto.entidade.Gasto;
import com.quantoeugasto.entidade.Mes;
import com.quantoeugasto.entidade.Usuario;

@Repository
public class GastoDAO extends Persistencia<Gasto> {
	
	@SuppressWarnings("unchecked")
	public List<Gasto> findGastos (Usuario usuario, Ano ano, Mes mes){
		Query q = this.getEm().createQuery("SELECT g FROM Gasto g JOIN g.categoria c WHERE c.usuario.username = :user AND g.ano.id = :ano AND g.mes = :mes ORDER BY g.data");
		q.setParameter("user", usuario.getUsername());
		q.setParameter("ano", ano.getId());
		q.setParameter("mes", mes);
		
		return q.getResultList();
	}
	
	@SuppressWarnings("rawtypes")
	public List<Map<String, Object>> findGastos (Usuario usuario, Ano ano){
		Query q = this.getEm().createQuery("SELECT sum(g.valor), c.nome, c.id, g.mes AS mes FROM Gasto g JOIN g.categoria c WHERE c.usuario.username = :user AND g.ano.id = :ano GROUP BY  c.nome, c.id, g.mes");
		q.setParameter("user", usuario.getUsername());
		q.setParameter("ano", ano.getId());
		
		List<Map<String, Object>> result = new LinkedList<Map<String,Object>>();
		
		for (Iterator i = q.getResultList().iterator(); i.hasNext();) {
			Object[] elementos = (Object[]) i.next();
			Map<String, Object> item = new HashMap<String, Object>();
			
			item.put("valor", new Double(elementos[0].toString()));
			item.put("nomeCategoria", elementos[1].toString());
			item.put("idCategoria", new Long(elementos[2].toString()));
			item.put("mes", elementos[3]);
			result.add(item);
		}
		
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Gasto> findGastos (Usuario usuario){
		Query q = this.getEm().createQuery("SELECT g FROM Gasto g JOIN g.categoria c WHERE c.usuario.username = :user ORDER BY g.id");
		q.setParameter("user", usuario.getUsername());
		
		return q.getResultList();
	}

}
